package com.cheyun.netsalev3.viewmodel.orderlist

import android.content.Context
import android.content.Intent
import android.util.Log
import android.view.View
import android.widget.DatePicker
import android.widget.TimePicker
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.LiveData
import androidx.lifecycle.Transformations
import androidx.paging.PagedList
import com.cheyun.netsalev3.bean.CustomListParam
import com.cheyun.netsalev3.bean.order.OrderData
import com.cheyun.netsalev3.bean.order.OrderDetail
import com.cheyun.netsalev3.repository.OrderListRepository
import com.cheyun.netsalev3.utils.FunctionUtils
import com.cheyun.netsalev3.utils.MySharedPreferences
import com.cheyun.netsalev3.utils.api.NetworkState
import com.cheyun.netsalev3.view.orderlist.OrderDetailsActivity
import com.cheyun.netsalev3.viewmodel.BaseViewModel
import com.cheyun.netsalev3.widget.DatePickerFragment
import com.cheyun.netsalev3.widget.MyContentDialog
import com.cheyun.netsalev3.widget.TimePickerFragment

/**
 * @author Michael
 * @date  2018/12/17 - 14:45.
 */
class OrderListFragmentViewModel(var repository: HashMap<String, OrderListRepository>) : BaseViewModel() {


    protected var TAG = javaClass.simpleName

    //选中的列表数据
    var pagedlist = HashMap<String, LiveData<PagedList<OrderData>>>()
    var hashMap = HashMap<String, LiveData<NetworkState>>()
    var totlelist = HashMap<String, LiveData<Int>>()

    var activity: AppCompatActivity? = null

    var year = ""
    var month = ""
    var day = ""

    var btnType = 0
    var currentOrder:OrderData? = null
    var currentView:View? = null

    init {
        for (key in repository.keys) {
            repository[key]?.apply {
                pagedlist[key] = this.loadAndroidData(null)
            }
        }
    }

    init {
        for (item in repository.keys) {
            pagedlist[item]?.apply {
                hashMap[item] = Transformations.switchMap(this) { repository[item]!!.networkState }!!
                totlelist[item] = Transformations.switchMap(this) { repository[item]!!.total }!!
            }
        }
    }

    var poplists = MySharedPreferences.getListItem()

    //自定义选项返回
    fun onResult(list: List<CustomListParam>) {
        poplists.clear()
        poplists.addAll(list)
    }
    fun initData(nkey: String) {
        Log.i(TAG,"initData ,"+ nkey)
        repository[nkey]?.apply {
//            this.setEanbleLoad(true)
            this.dataSourceFactory.sourceLiveData.value?.invalidate()
        }
    }

    /**
     * 刷新
     */
    fun refresh(nkey: String,hashMap:HashMap<String, String>? = null) {
        if(hashMap != null) {
            repository[nkey]?.changeMap(hashMap)
        }
        repository[nkey]?.dataSourceFactory?.sourceLiveData?.value?.invalidate()
    }

    /**
     * 点击item
     */
    fun onClickItem(view: View, item: OrderData) {
        var intent = Intent(view.context, OrderDetailsActivity::class.java)
        intent.putExtra("oid", item.id)
        intent.putExtra("tid", item.tid)
        view.context.startActivity(intent)
    }

    fun onConfrimTime(view: View,item: OrderData) {
        if(item.ischange == 5){
            MyToast("已提交至DMS换车中，请先至DMS完成交期答复并在同步DMS订单")
            return
        }
        btnType = 1
        currentOrder = item
        var content = view.context
        if (content is AppCompatActivity) {
            activity = content
            val datePickerFragment = DatePickerFragment()
            datePickerFragment.clickOk = this::onDateSet
            datePickerFragment.show(content.supportFragmentManager, "datePicker")
        }
    }

    //整备完成
    fun onServicing(view: View,item:OrderData){
        if(item.ischange == 5){
            MyToast("已提交至DMS换车中，请先至DMS完成交期答复并在同步DMS订单")
            return
        }
        currentOrder = item
        var context = view.context
        if (context is AppCompatActivity) {
            var pop = MyContentDialog.newInstance("整备完成", "是否确认整备完成？")
            pop.onClickOk = this::popServicingOk
            pop.show(context.supportFragmentManager, "")
        }
    }
    fun popServicingOk(){
        var moth: () -> Unit = {
            refresh(currentOrder?.cararrive.toString())
        }
        var fail: () -> Unit = {

        }
        repository[currentOrder?.cararrive.toString()]?.servicing(currentOrder?.id.toString(),moth,fail)
    }

    /**
     * 点击日期回调
     */
    fun onDateSet(view: DatePicker, year: Int, month: Int, day: Int) {
        this.year = year.toString()
        this.month = month.toString()
        this.day = day.toString()
        val timePickerFragment = TimePickerFragment()
        timePickerFragment.clickOk = this::onTimeSet
        timePickerFragment.show(activity?.supportFragmentManager!!, "timePicker")
    }

    /**
     * 点击时间回调
     */
    fun onTimeSet(view: TimePicker, hourOfDay: Int, minute: Int) {
        var time = FunctionUtils.formatTime(year, month, day, hourOfDay, minute)

        var moth: () -> Unit = {
            refresh(currentOrder?.cararrive.toString())
        }
        var fail: () -> Unit = {

        }
        repository[currentOrder?.cararrive.toString()]?.confirmCartime(currentOrder?.id.toString(),time,moth,fail)

    }

    fun onEditTime(view: View,item: OrderData) {
        if(item.ischange == 5){
            MyToast("已提交至DMS换车中，请先至DMS完成交期答复并在同步DMS订单")
            return
        }
        btnType = 2
        currentOrder = item
        var content = view.context
        if (content is AppCompatActivity) {
            activity = content
            val datePickerFragment = DatePickerFragment()
            datePickerFragment.clickOk = this::onDateSet
            datePickerFragment.show(content.supportFragmentManager, "datePicker")
        }
    }


    fun onJiaoche(view: View,item:OrderData){
        if(item.ischange == 5){
            MyToast("已提交至DMS换车中，请先至DMS完成交期答复并在同步DMS订单")
            return
        }
        currentOrder = item
        currentView = view
        var context = view.context
        if (context is AppCompatActivity) {
            if(item.isimmed==1){
                onClickItem(view,item)
            }else {
                var pop = MyContentDialog.newInstance("立即交车", "是否确认要立即交车？")
                pop.onClickOk = this::popOk
                pop.show(context.supportFragmentManager, "")
            }
        }
    }

    fun popOk(){
        var moth: () -> Unit = {
            onClickItem(currentView!!,currentOrder!!)
            refresh(currentOrder?.cararrive.toString())
        }
        var fail: () -> Unit = {

        }
        repository[currentOrder?.cararrive.toString()]?.addeliver(currentOrder?.id.toString(),moth,fail)
    }


}